package com.party.jackclientandroid.ui_mine.my_wallet;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.alipay.sdk.app.AuthTask;
import com.party.jackclientandroid.BaseActivityTitle;
import com.party.jackclientandroid.R;
import com.party.jackclientandroid.api.DefaultConsumer;
import com.party.jackclientandroid.api.UserService;
import com.party.jackclientandroid.base.MyException;
import com.party.jackclientandroid.bean.AppInfo;
import com.party.jackclientandroid.bean.BaseResult;
import com.party.jackclientandroid.bean.BindingInfo;
import com.party.jackclientandroid.bean.User;
import com.party.jackclientandroid.bean.VerifyUser;
import com.party.jackclientandroid.controller.DialogController;
import com.party.jackclientandroid.event.AuthResultEvent;
import com.party.jackclientandroid.wxapi.WXPayUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

public class BindingAccountZfbActivity extends BaseActivityTitle {

    @BindView(R.id.binding_btn)
    Button binding_btn;


    @BindView(R.id.wx_icon)
    CircleImageView wx_icon;


    UserService userService;

    BindingInfo mBindingInfo;

    Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_binding_ali);
        initData();
    }

    protected void initData() {
        setMiddleText("实名认证");
        userService = new UserService(this);
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                Map<String, String> result = (Map<String, String>) msg.obj;
                String resultStr = result.get("result");
                if (!resultStr.contains("&")) return;
                String[] split = resultStr.split("&");
                Map<String, String> mapData = new HashMap<>();
                for (int i = 0; i < split.length; i++) {
                    String[] split1 = split[i].split("=");
                    mapData.put(split1[0], split1[1]);
                }
                if (!"200".equals(mapData.get("result_code"))) {
                    showToast("授权失败");
                    return;
                }
                String auth_code = mapData.get("auth_code");
                bindingZfbUser(auth_code);
            }
        };

        TextView auth_real_name = findViewById(R.id.auth_real_name);
        auth_real_name.setOnClickListener((View v) -> {
            startActivity(RealNameAuthenticationActivity.class);
            finish();
        });
    }

    @OnClick(R.id.binding_btn)
    public void getAliAuthInfoStr(View v) {
        switch (v.getId()) {
            case R.id.binding_btn:
                addDisposableIoMain(userService.getAliAuthInfoStr(), new DefaultConsumer<String>(mApplication) {
                    @Override
                    public void operateSuccess(BaseResult<String> baseBean) {
                        String infoStr = baseBean.getData();
                        authTask(infoStr);
                    }

                    @Override
                    public void operateError(String message) {
                        super.operateError(message);
                    }
                });
                break;
        }
    }


    public void authTask(String infoStr) {
        new Thread(() -> {
            AuthTask authTask = new AuthTask(mActivity);
            Map<String, String> result = authTask.authV2(infoStr, true);
            Message msg = new Message();
            msg.obj = result;
            handler.sendMessage(msg);
        }).start();
    }


    /**
     * 使用授权code 去获取 用户信息
     *
     * @param auth_code
     */
    public void bindingZfbUser(String auth_code) {
        addDisposableIoMain(userService.checkZMScoreAndBindingAli(auth_code), new DefaultConsumer<BindingInfo>(mApplication) {
            @Override
            public void operateSuccess(BaseResult<BindingInfo> baseBean) {
                hideAlertDialog();
                mBindingInfo = baseBean.getData();
                User user = mApplication.getUser();
                user.setIsBindingAli(1);
                mApplication.setUser(user);
                mApplication.getImageLoaderFactory().loadCommonImgByUrl(mActivity, baseBean.getData().getAvatar(), wx_icon);
                authOk(mBindingInfo.getVerKey());
            }

            @Override
            public void operateError(String message) {
                DialogController.showConfirmDialog(mActivity, "温馨提示", message);
                super.operateError(message);

            }
        }, (Throwable throwable) -> {
            showToast(throwable.getMessage());
        });
    }


    public void authOk(String bindingKey) {
        showLoadingDialog();
        Intent intent = new Intent(mActivity, SetPayPasswordActivity.class);
        intent.putExtra("verKey", bindingKey);
        startActivity(intent);
        finish();
    }


}
